package com.gzx.spring.apis.tests.jishu;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Arrays;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson2.JSONObject;

public class ExtremeDataApiClient_ed006_v1 {
	private static final String API_URL = "http://api.extremedata.cn/router/predict";
	private static final String APP_KEY = "gzx20250728134819"; // 替换为实际appKey
	private static final String APP_SECRET = "7265b1d037c51cd35a5586900c364a31"; // 替换为实际appSecret

	public static String md5(String input) throws Exception {
		// 创建MD5算法的MessageDigest实例
		MessageDigest md = MessageDigest.getInstance("MD5");

		// 将输入字符串转换为字节数组并进行MD5摘要计算
		byte[] messageDigest = md.digest(input.getBytes());

		// 将字节数组转换为十六进制字符串表示
		BigInteger no = new BigInteger(1, messageDigest);
		String hashtext = no.toString(16);

		// 如果十六进制字符串长度小于32位，在前面补0
		while (hashtext.length() < 32) {
			hashtext = "0" + hashtext;
		}

		return hashtext;
	}

	public static String buildCustSign(JSONObject reqJson, String appSecret) throws Exception {
		reqJson.remove("sign");
		char[] charArray = JSONObject.toJSONString(reqJson).toCharArray();
		Arrays.sort(charArray);
		String signStr = new String(charArray);
		signStr = String.format("%s%s", signStr, appSecret);
		return md5(signStr);
	}

	public static void main(String[] args) {
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			// 1. 准备业务参数
			JSONObject reqJson = new JSONObject();
			reqJson.put("phoneMd5", md5("13800138000")); // 示例：手机号MD5
			reqJson.put("idNoMd5", md5("340821199010102423")); // 可选：身份证MD5
//            reqJson.put("nameMd5", md5("张三")); // 可选：姓名MD5

			// 2. 准备公共参数
			String timestamp = String.valueOf(Instant.now().toEpochMilli());
//            String sign = buildCustSign(reqJson, APP_SECRET);

			// 3. 构建完整请求体
			JSONObject requestBody = new JSONObject();
			requestBody.put("appKey", APP_KEY);
			requestBody.put("pName", "ed006_v1"); // 根据文档，pName固定为demo
			requestBody.put("timestamp", timestamp);
			requestBody.put("reqJson", reqJson);
			String sign = buildCustSign(requestBody, APP_SECRET);
			requestBody.put("sign", sign);

			// 4. 创建HTTP请求
			HttpPost httpPost = new HttpPost(API_URL);
			httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
			httpPost.setEntity(new StringEntity(requestBody.toString(), StandardCharsets.UTF_8));

			// 5. 执行请求并处理响应
			try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
				int statusCode = response.getStatusLine().getStatusCode();
				String responseBody = EntityUtils.toString(response.getEntity());

				System.out.println("响应状态码: " + statusCode);
				System.out.println("响应内容: " + responseBody);

				// 6. 解析响应
				JSONObject result = JSONObject.parseObject(responseBody);
				String code = result.getString("code");

				switch (code) {
				case "200":
					JSONObject data = result.getJSONObject("data");
					String score = data.getString("score");
					System.out.println("请求成功，评分: " + score);
					break;
				case "1001":
					System.out.println("查询成功，但匹配结果为空");
					break;
				case "1005":
					System.err.println("错误: IP白名单未添加，请联系数据方添加IP白名单");
					break;
				default:
					System.err.println("请求失败，错误码: " + code + ", 消息: " + result.get("msg"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
